<script setup lang="ts">
// @ts-nocheck
import Icon from "./wechat_2025-05-02_144815_538.png";
import dayjs from "dayjs";
import api from "../api/index.js";

import { ref, onMounted } from "vue";
import { UploaderInstance } from "vant"; // 引入 Uploader 类型定义
const waitFile = ref(null);
const uploader = ref<UploaderInstance | null>(null);
const loading = ref(false);

const list = ref([
  //   {
  //     Id: 1,
  //     filename: "2023-05-17 14_30.pdf",
  //     sumbitTime: "2023-05-17 14:30",
  //     size: "29M",
  //   },
  //   {
  //     Id: 2,
  //     filename: "2023-05-17 14_30.pdf",
  //     sumbitTime: "2023-05-17 14:30",
  //     size: "29M",
  //   },
]);

//更新历史记录
const updateHistoryList = (arr) => {
  list.value = arr;
  window.localStorage.setItem("historyList", JSON.stringify(arr));
};

onMounted(() => {
  const historyList = window.localStorage.getItem("historyList");
  if (historyList) {
    list.value = JSON.parse(historyList);
  } else {
    list.value = [];
  }
});

const show = ref(false);
const showPopup = () => {
  show.value = true;
};

// 返回布尔值
const beforeRead = (file) => {
  console.log("上传文档：", file);
  file.value = file;

  //   if (file.type !== "pdf") {
  //     showToast("请上传PDF文档");
  //     return false;
  //   }
};

const afterRead = (file) => {
  // 此时可以自行将文件上传至服务器
  console.log("文件读取成功：", file);
  waitFile.value = file;

  showConfirmDialog({
    title: "提示",
    message: "文件读取成功，提交转换吗？",
  })
    .then(() => {
      // on confirm
      uploadFiles();
    })
    .catch(() => {
      // on cancel
    });
};
const onOversize = (file) => {
  console.log(file);
  showToast("文件大小不能超过 100MB");
};

//插入一条历史记录并更新缓存
const addHistory = (item) => {
  list.value.unshift(item);
  updateHistoryList(list.value);
};

const uploadFiles = async () => {
  if (waitFile.value) {
    loading.value = true;
    const { name, size } = waitFile.value.file;
    console.log("文件大小：", size);
    if (size > 3 * 1024 * 1024) {
      showToast("文件太大了，不能超过3MB！");
      loading.value = false;
      return;
    }
    const res = await api.uploadFile({
      files: waitFile.value.file,
    });
    loading.value = false;
    showToast("提交成功！");
    console.log("提交转换成功", res);
    addHistory({
      name: name,
      size: size,
      sumbitTime: dayjs().format("YYYY-MM-DD HH:mm"),
      id: res.data.data.id,
    });
  } else {
    showToast("请选择文件！");
  }
};

//删除一条历史记录并更新缓存
const deleteHistory = (id) => {
  showConfirmDialog({
    title: "重要提示",
    message: "确认已经下载文档，删除历史记录后无法找回，你确定要删除吗？",
  })
    .then(() => {
      // on confirm
      console.log("删除历史记录", id);
      let arr = list.value.filter((item) => {
        console.log("过滤：", item.id);
        return item.id !== id;
      });
      console.log("删除后的数据：", arr);
      updateHistoryList(arr);
    })
    .catch(() => {
      // on cancel
    });
};

//转换结果查看弹窗打开按钮
const url = ref(null);
const loadingResult = ref(false);
const showBottom = ref(false);
const openResult = async (id) => {
  try {
    loadingResult.value = true;
    showBottom.value = true;
    const res = await api.getDetail(id);
    console.log("转换结果：", res);
    if (res.data.url && res.data.url.length > 0) {
      url.value = res.data.url;
      showToast("已经转换成功！可点击下载按钮下载");
    } else {
      url.value = null;
    }
  } catch (error) {
    url.value = null;
  }
};

const downloadFile = () => {
  window.open(url.value);
  showBottom.value = false;
};
//查询结果
</script>

<template>
  <div class="page">
    <van-uploader
      :deletable="true"
      ref="uploader"
      :read-only="true"
      class="uploader"
      style="width: 100%"
      :after-read="afterRead"
      :max-count="1"
      @oversize="onOversize"
      :max-size="100000 * 1024"
    >
      <div class="container">
        <div class="center">
          <img :src="Icon" class="icon" alt="" />
          <span class="text">点击上传PDF文件至此处</span>
        </div>
      </div>
    </van-uploader>
    <div class="action">
      <!-- <div class="action-container">
        <van-button
          :loading="loading"
          block
          type="primary"
          @click="uploadFiles()"
          >提交转换</van-button
        >
      </div> -->
    </div>
    <!-- 文档转换结果弹窗查看 -->
    <van-popup
      v-model:show="showBottom"
      position="top"
      :style="{ height: '40%' }"
    >
      <van-empty v-if="url == null" description="暂无转换结果，请稍后" />
      <div v-else class="result">
        <van-button type="primary" @click="downloadFile()">下载</van-button>
        <div>转换完成，点击下载按钮下载文档</div>
      </div>
    </van-popup>
    <!-- 说明 -->
    <div style="padding: 0 10px">
      <div>
        <h4>说明</h4>
      </div>
      <div>
        提交后请在24小时内通过点击查看按钮查看转换状态是否转换完成，超时将下载失败，文件不保存任何服务器，历史记录仅保存在您本地，请在下载文件前不要清理缓存
      </div>
    </div>

    <!-- 文档转换结果弹窗查看 -->
    <div class="history-list">
      <div class="header">
        <h4>历史记录</h4>
      </div>
      <div class="list-item" v-for="(item, index) in list">
        <div class="item-container">
          <div class="header">文件名称：{{ item.name }}</div>
          <div class="center">
            <div class="left">
              <span class="submit-time"> 提交时间：{{ item.sumbitTime }} </span>
              <span class="submit-time"> 文件大小：{{ item.size }} </span>
            </div>
            <div class="right">
              <!-- <van-button
                size="mini"
                type="primary"
                @onclick="showPopup(item.id)"
                >查看</van-button
              > -->
            </div>
          </div>

          <div class="bottom-btn">
            <van-button  size="small" type="primary" @click="openResult(item.id)"
              >查看</van-button
            >
            <van-button size="small" type="danger" @click="deleteHistory(item.id)"
              >删除</van-button
            >
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="scss">
.result {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.page {
  width: 100%;

  .uploader {
    width: 100%;
    .van-uploader__input-wrapper {
      width: 100% !important;
      .container {
        width: 100%;
        height: 180px;
        padding: 10px;

        .center {
          width: 100%;
          height: 100%;
          border: 1px dashed #419ee479;
          display: flex;
          flex-direction: column;
          justify-content: center;
          align-items: center;
          .icon {
            width: 50px;
            height: 50px;
            padding: 10px;
          }
          .text {
          }
        }
      }
    }
  }
  .action {
    width: 100%;
    padding: 10px;
    .action-container {
      width: 100%;
    }
  }
  .history-list {
    width: 100%;
    padding: 10px;
    .list-item {
      padding: 5px 0;
      .item-container {
        width: 100%;

        background-color: #f5f5f5;
        padding: 5px;
        .header {
          width: 100%;
        }
        .center {
          width: 100%;
          display: flex;
          .left {
            flex: 1;
            .submit-time {
            }
          }
          .right {
            width: 40px;
          }
        }
        .bottom-btn {
          padding: 10px 0;
          display: flex;
          justify-content: space-between;
        }
      }
    }
  }
}
</style>
